<?php

namespace App\Exports;


use App\Models\CarModels\CarInfo;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use PhpOffice\PhpSpreadsheet\Cell\Cell;
use Maatwebsite\Excel\Concerns\ToModel;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;
class CommonExport extends DefaultValueBinder implements FromCollection,WithHeadings,WithMapping,WithCustomValueBinder
{
    use Exportable;
    protected $headers;
    protected $cls;
    public function __construct($headers,$cls)
    {
        $this->cls = $cls;
        $this->headers = $headers;
    }

    public function collection()
    {
        return $this->cls::all();
    }

    public function headings(): array
    {
        return array_values($this->headers);
    }


    public function map($invoice): array
    {
        $arr = [];
        foreach ($this->headers as $k=>$value){
            $k_arr = explode("->",$k);
            $tmp_v = $invoice->{"$k_arr[0]"};
            //切片数组 如果数组有几个 比如 car->kind->name那么就运行该代码
            if(sizeof($k_arr) > 1){
                foreach (array_slice($k_arr,1) as $v){
                    $tmp_v = $tmp_v->{"$v"};
                }
            }
            array_push($arr,$tmp_v);
        }
        return $arr;
    }


    //1. 调拨 2.借用 3.使用中 4. 停运
    public function bindValue(Cell $cell, $value)
    {
        Log::info($value);
        $colunm = $cell->getColumn();//获取所在的列
        $headerIndex = ord($colunm) - ord("A"); //获取所在的列对应header在哪个位置
        $headerArr = explode('|',$this->headings()[$headerIndex]);
        if(sizeof($headerArr) > 1){
            if($value == 1)
                $x = 1;
            $map_json = $headerArr[1];
            $map = json_decode($map_json);
            foreach ((array) $map as $v){
                if(array_key_exists($value,array($v)))
                    $value = (array) $v[$value];
            }
        }
        // else return default behavior
        return parent::bindValue($cell, $value);
    }
}
